<?php
/**
 * @property integer $id
 * @property string $name
 * @property string $description
 * @property string $install
 *
 * The followings are the available model relations:
 * @property DevFiles[] $devFiles
 */
class Dev extends CActiveRecord
{
    public $files;
    
    /*public function behaviors()
    {
        return array(
            'fileMultiUploader' => array(
                'class'=>'components.behaviors.fileMultiUploader',
                'path'=>'upload',
                'field'=>'field'
            ),
        );
    }*/
    
	public function tableName()
	{
		return 'dev';
	}

	public function rules()
	{
		return array(
            array('files', 'file', 
                'types'=>'jpg,jpeg,gif,png,doc,docx,pdf,txt',
                'maxSize'=>1024 * 1024 * 1, // 1MB
                'tooLarge'=>'The file was larger than 1MB. Please upload a smaller file.',
                'allowEmpty'=>1,
            ),
			array('name, description, install', 'required'),
			array('name', 'length', 'max'=>100),
			array('id, name, description, install', 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
			'devFiles' => array(self::HAS_MANY, 'DevFiles', 'dev_id'),
		);
	}

	public function attributeLabels()
	{
		return array(
			'id'          => 'ИД',
			'name'        => 'Название',
			'description' => 'Описание',
			'install'     => 'Установка',
            'files'       => 'Файлы',
		);
	}

	public function search()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('install',$this->install,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
    
    public function afterSave()
    {
       $this->files = CUploadedFile::getInstancesByName('files');
       if (!empty($this->files)) {
            foreach ($this->files as $k => $file) {
                //echo $file->name.'<br />';
                if ($src = $file->saveAs(Yii::getPathOfAlias('webroot').'/upload/'.$file->name)) {
                    $devFiles = new DevFiles();
                    $devFiles->name = $file->name;
                    $devFiles->src = $src;
                    $devFiles->dev_id = $this->id;
                    if (!$devFiles->save()) {
                        var_dump($devFiles->errors);
                        return false;
                    }
                }
            }
        }
       return parent::afterSave();
    }
}
